package com.ruoyi.auth.listener;

import com.ruoyi.common.core.utils.HttpRequestUtil;
import com.ruoyi.common.security.domain.LoginUser;
import com.ruoyi.system.api.model.dto.SysLoginLogDto;
import com.ruoyi.system.api.service.ILogApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Autowired
    ILogApiService logApiService;

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {

        //这里的事件源除了登录事件（UsernamePasswordAuthenticationToken）还有可能是token验证事件源（OAuth2Authentication）
        if (!event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")) {
            return;
        }

        //这里还有oAuth2的客户端认证的事件，需要做一个判断
        if (event.getAuthentication().getDetails() != null) {
            if (event.getAuthentication().getPrincipal().getClass().equals(LoginUser.class)) {
                LoginUser loginUser = (LoginUser) event.getAuthentication().getPrincipal();
                //登录日志逻辑。。。
                log.info(loginUser.getUsername() + " 登录成功");
                SysLoginLogDto sysLoginLog = new SysLoginLogDto();
                sysLoginLog.setUserId(loginUser.getUserId());
                sysLoginLog.setUserName(loginUser.getUsername());
                sysLoginLog.setMsg("登录成功");
                sysLoginLog.setStatus("0");
                sysLoginLog.setIpAddr(HttpRequestUtil.getAddr());
                sysLoginLog.setBrowser(HttpRequestUtil.getBrowser());
                sysLoginLog.setOs(HttpRequestUtil.getOs());
                logApiService.saveLoginLog(sysLoginLog);
            }

        }
    }

}
